import axios from 'axios';
import Vue from 'vue'
import router from '../router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
// import qs from 'qs';
let http = axios.create({
    // baseURL: 'http://192.168.1.20:8899/',
    baseURL: 'https://api.ok68.vip',
    withCredentials: true,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    },
    transformRequest: [function(data) {
        let newData = '';
        for (let k in data) {
            if (data.hasOwnProperty(k) === true) {
                newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&';
            }
        }
        return newData;
    }]
});
http.interceptors.request.use((config) => {
    return config;
}, (error) => {
    return Promise.reject(error);
});
http.interceptors.response.use((res) => {
    if (res.data.code == 403) {
        Vue.prototype.$message.error(res.data.msg);
        router.replace({ path: "/" });
    } else if (res.data.code !== 200 && res.data.code !== 403) {
        Vue.prototype.$message.error(res.data.msg);
    }
    return res;
}, (error) => {
    //404等问题可以在这里处理
    Vue.prototype.$message.error("网络延迟,请稍后再试！");
    return Promise.reject(error);
});

function apiAxios(method, url, params, response) {
    http({
        method: method,
        url: url,
        data: method === 'POST' ? params : null,
        params: method === 'GET' ? params : null,
    }).then(function(res) {
        response(res);
    }).catch(function(err) {
        response(err);
    })
}

export default {
    get: function(url, params, response) {
        return apiAxios('GET', url, params, response)
    },
    post: function(url, params, response) {
        return apiAxios('POST', url, params, response)
    }
}